<?php

class Safety_PrivilegeController extends App_Controller_Action
{

	public function init()
    {
    	parent::init();
    }

    public function indexAction()
    {
        $this->_helper->redirector('read');
    }
    
	/**
	 * This action shows a paginated list roles
	 */
	public function readAction() 
	{
		$query = $this->_entityManager->createQuery('select u from \model\Role u');
		$this->view->roles = $query->getResult();
	}
	
	/**
	 * This action is call by the XHR
	 * 
	 * Handles create requests.
	 */
	public function createSaveAction() 
	{
        $this->_helper->viewRenderer->setNoRender(true);
        if ($this->_request->isPost()) {
            $form = new Safety_Form_Privilege();
            if ($form->isValid($_POST)) {
                try {
                	// new main group
                    $privilege = new \model\Privilege();
                	$privilege->setModule($this->_getParam('moduleFilter',''));
                	$privilege->setController($this->_getParam('controllerFilter',''));
                	$privilege->setAction($this->_getParam('actionFilter',''));
                	
                	$role = $this->_entityManager->find('model\Role', $this->_getParam('roleFilter',0));
                	$privilege->setRole($role);
                	
                	$this->_entityManager->persist($privilege);
                	$this->_entityManager->flush();
                	// response to client
                	$this->view->success = true;
                    $this->_messenger->addSuccess(_("Their data were processed successfully."));
                    $this->view->message = $this->view->seeMessages();
                } catch (Exception $e) {
                	$this->_logger->err($e->getMessage());
                	// response to client
                	$this->view->success = false;
                    $this->_messenger->addError(_("An error occurred while processing the data. <br/> Please Try again."));
                    $this->view->message = $this->view->seeMessages();
                }
            } else {
            	// response to client
                $this->view->success = false;
            	$this->_messenger->addError(implode("<br/>", $form->getMessages()));
                $this->view->message = $this->view->seeMessages();
            }
        } else {
        	// response to client
        	$this->_messenger->addNotice(_("Data submitted were not processed."));
        	$this->view->success = false;        	
        	$this->view->message = $this->view->seeMessages();
        }
        // send response to client
        $this->_helper->json($this->view);
	}
	
	/**
	 * This is action is an XHR action
	 * 
	 *  When requested it will delete Roles with the ids found in the payload array.
	 */
	public function deleteAction() 
	{
		$this->_helper->viewRenderer->setNoRender(true);
        if ($this->_request->isPost()) {
            $options = $this->_getParam('privileges',array());
            if ( !empty($options) ) {
                try {
                	$roleRepository = $this->_entityManager->getRepository('model\Privilege');
                	$roleRepository->deleteItems($options);                	
                	// response to client
                	$this->view->success = true;
                    $this->_messenger->addSuccess(_("Their data were processed successfully."));
                    $this->view->message = $this->view->seeMessages();
                } catch (Exception $e) {
                	$this->_logger->err($e->getMessage());
                	// response to client
                	$this->view->success = false;
                    $this->_messenger->addError(_("An error occurred while processing the data. <br/> Please Try again."));
                    $this->view->message = $this->view->seeMessages();
                }
            } else {
            	// response to client
                $this->view->success = false;
            	$this->_messenger->addNotice(_("Data submitted is empty."));
                $this->view->message = $this->view->seeMessages();
            }
        } else {
        	// response to client
        	$this->_messenger->addNotice(_("Data submitted were not processed."));
        	$this->view->success = false;        	
        	$this->view->message = $this->view->seeMessages();
        }
        // send response to client
        $this->_helper->json($this->view);
	}
	
	/**
	 * 
	 */
	public function readItemsAction() {
//		$this->_helper->viewRenderer->setNoRender();
		$role_id = $this->_getParam('role',0);
		if ( !$role_id ) {
			$query = $this->_entityManager->createQuery('select p from \model\Privilege p');
		} else {
			$query = $this->_entityManager->createQuery('select p from \model\Privilege p where p.role = :role_id')->setParameter('role_id', $role_id);
			
		}
		//$this->_logger->err($query->getSQL());
		//paginacion
		$adapter = new App_Paginator_Adapter_Doctrine($query);
		$paginator = new Zend_Paginator($adapter);
		
		$start = $this->_getParam('iDisplayStart', 0);
        $limit = $this->_getParam('iDisplayLength', 10);
        $page = ($start + $limit) / $limit;
        // show page
		$paginator->setCurrentPageNumber($page);
		// show n items by page
		$paginator->setItemCountPerPage($limit);
		
		// output
		$this->view->sEcho = intval($_GET['sEcho']);
		$this->view->iTotalRecords = $paginator->getTotalItemCount();
		$this->view->iTotalDisplayRecords = $paginator->getTotalItemCount();
		$this->view->aaData = array();
		foreach ($paginator as $t) {
			$row = array();
			$row[] = $t->getId();
			$row[] = $t->getModule();
			$row[] = $t->getController();
			$row[] = $t->getAction();
			
			$this->view->aaData[] = $row;
		}
		$this->_helper->json($this->view);
	}
}

